package com.glory.brepda.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.glory.brepda.R;
import com.glory.brepda.activity.recipe.RecipeUpImageActivity;
import com.glory.brepda.activity.recipe.SolderJointUpImageActivity;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.AuthorityListEntity;
import com.glory.brepda.entity.LoginEntity;
import com.glory.brepda.entity.UpdateIPEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.EditTextEnterUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;

import java.io.DataOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * FileName: LoginActivity
 * Author: XJH
 * Date: 2020/5/12 10:45
 * Description: 登录界面
 * History:
 */
public class LoginActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.ivSetting)
    ImageView ivSetting;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;

    private static final int PERMISSIONS_REQUEST_CODE = 10;
    private int code;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

        FreeApi_LogUtils.saveErrorMessages((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)).format(new Date()),"时间---");

        Constant.REQUEST_URL_DEBUG = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "REQUEST_URL_DEBUG", Constant.REQUEST_URL_DEBUG, com.glory.brepda.base.MyApp.app);
        Constant.REQUEST_MES = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "REQUEST_MES", Constant.REQUEST_MES, com.glory.brepda.base.MyApp.app);
        Constant.FILE_URL = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "FILE_URL_DEBUG", Constant.FILE_URL, com.glory.brepda.base.MyApp.app);
        Constant.CURRENT_USER  = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "CURRENT_USER", MyApp.app);
//        etUser.setText(Constant.CURRENT_USER);
        initEditNotToUpperCase(etUser, s->{
            if(s.contains(",")){
                String[] split = s.split(",");
                etUser.setText(split[0]);
                etPassword.setText(split[1]);
                login();
            }
        });
    }



        @Override
    protected void initData() {
//            login();
        requestPermission();

        // 获取系统时间
//        getSystemTime();

        //比对版本
        detectionUpdate();
    }

    private void getSystemTime() {
        FreeUI_EntityCallBack<BaseResponseBean<Object>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<Object>>
                (new TypeToken<BaseResponseBean<Object>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<Object>> response) {
                super.onSuccess(response);
                String time = response.body().getResponse().getReturn().getReturnMessage();
                time = time.replace("/","");
                time = time.replace(":","");
                time = time.replace(" ",".");

                updateSysTime(time);
            }

            @Override
            public void onError(Response<BaseResponseBean<Object>> response) {
                super.onError(response);
                loadError(response.getException(), "GetDateTime");
            }
        };

        JsonObject map = new JsonObject();
        NetUtils.requestPostNet("GetDateTime", "GetDateTime",LoginActivity.this, map, callBack);

    }

    private void clear(){
        SharedPreferences sharedPreferences =  getSharedPreferences("DG_CPC_FILE", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.clear();
        edit.commit();
    }

    private void getPermission(String userName) {
        FreeUI_EntityCallBack<BaseResponseBean<AuthorityListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AuthorityListEntity>>
                (new TypeToken<BaseResponseBean<AuthorityListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AuthorityListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    Constant.AUTHORITY_ENTITY = response.body().getResponse().getBody();
                    if (Constant.AUTHORITY_ENTITY != null){
                        FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "CURRENT_USER", etUser.getText().toString().trim(), getApplicationContext());
                        showToast("登陆成功", true);
                        Constant.CURRENT_USER = userName;
                        FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, MainActivity.class);
                        finish();
                    }else {
                        etUser.setText("");
                        etPassword.setText("");
                        etUser.requestFocus();
                        showToast("当前登录人员无任何权限!", false);
                    }

                }
            }

            @Override
            public void onError(Response<com.glory.brepda.entity.response.BaseResponseBean<com.glory.brepda.entity.AuthorityListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"USER_GETAUTHORITY");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("NAME",userName);
        jsonObject.addProperty("AUTHORITYCATEGORY","PDA");
        NetUtils.requestPostNet("IF.USER_GETAUTHORITY","Common",LoginActivity.this,jsonObject,callBack);
//        NetUtils.requestMESPostNet("SYS.USER_GETAUTHORITY",this,jsonObject,callBack);

    }

    private void detectionUpdate()    {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                code = compareVersion(version,entity.getVersion());
                if(code == -1 ||code == 1) {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(),"DOWNLOAD");
                }

            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(Constant.FILE_URL, this, map, callBack);
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        } else {
            String[] version1Array = version1.split("\\.");
            String[] version2Array = version2.split("\\.");
            Log.d("HomePageActivity", "version1Array==" + version1Array.length);
            Log.d("HomePageActivity", "version2Array==" + version2Array.length);
            int index = 0;
            int minLen = Math.min(version1Array.length, version2Array.length);
            int diff = 0;
            Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);

            while(index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
                ++index;
            }

            if (diff == 0) {
                int i;
                for(i = index; i < version1Array.length; ++i) {
                    if (Integer.parseInt(version1Array[i]) > 0) {
                        return 1;
                    }
                }

                for(i = index; i < version2Array.length; ++i) {
                    if (Integer.parseInt(version2Array[i]) > 0) {
                        return -1;
                    }
                }

                return 0;
            } else {
                return diff > 0 ? 1 : -1;
            }
        }
    }


    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private void requestPermission(){
        //Manifest.permission.READ_PHONE_STATE 申请不到
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE};
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            //login();
        }else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(this, "程序运行需要权限",
                    PERMISSIONS_REQUEST_CODE, perms);
        }
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        showToast("用户授权失败",false);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @OnClick({R.id.ivSetting, R.id.btnLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivSetting:
                FreeApi_Utils.skipWithExtraIntent("header", LoginActivity.this, SettingActivity.class);
                break;
            case R.id.btnLogin:
                if (etUser.getText().toString().trim().length() == 0){
                    showToast("请输入用户名",false);
                    return;
                }

                if (etPassword.getText().toString().trim().length() == 0){
                    showToast("请输入密码",false);
                    return;
                }
//                FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, SolderJointUpImageActivity.class);
                login();
                break;
        }
    }

    private void login() {
        FreeUI_EntityCallBack<BaseResponseBean<LoginEntity>> callBack = new FreeUI_DialogEntityCallBack<com.glory.brepda.entity.response.BaseResponseBean<LoginEntity>>
                (new TypeToken<BaseResponseBean<LoginEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LoginEntity>> response) {
                super.onSuccess(response);
                if (response.body().getResponse().getHeader().getRESULT().toUpperCase().equals("SUCCESS")) {
                    if (response.body() != null) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            Constant.CURRENT_USER = response.body().getResponse().getBody().getUSER().getUSERNAME();
                            Constant.CURRENT_DESC = response.body().getResponse().getBody().getUSER().getDESCRIPTION();
                            if (!response.body().getResponse().getBody().getLOGINRESULT()) {
                                showToast("登录失败", true);
                            } else {
                                //权限获取
                                getPermission(response.body().getResponse().getBody().getUSER().getUSERNAME());
                            }
                        }
                    } else {
                        showToast("暂无登陆信息，请检查地址是否正确！", true);
                    }
                }else {
                    showToast(response.body().getResponse().getHeader().getRESULTMESSAGE(), true);
                }
//                login();
            }

            @Override
            public void onError(Response<BaseResponseBean<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"USER_LOGIN");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("USERNAME",etUser.getText().toString().trim());
        jsonObject.addProperty("PASSWORD",etPassword.getText().toString().trim());
        NetUtils.requestPostNet("IF.BRELOGIN","Common",LoginActivity.this,jsonObject,callBack);
//        NetUtils.requestMESPostNet("IF.BRELOGIN",this,jsonObject,callBack);


    }

    public void updateSysTime(String time){
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            //os.writeBytes("setprop persist.sys.timezone GMT\n");
            os.writeBytes("/system/bin/date -s " + time + "\n");
            os.writeBytes("clock -w\n");
            os.writeBytes("exit\n");
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SimpleDateFormat")
    public void setSystemTime(String time){

        ArrayList<String> envlist = new ArrayList<String>();
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            envlist.add(envName + "=" + env.get(envName));
        }
        String[] envp = (String[]) envlist.toArray(new String[0]);
        String command;
        command = "date -s\""+time+"\"";
        try {
            Runtime.getRuntime().exec(new String[] { "su", "-c", command },
                    envp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
